package com.assets.Repairs;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.assets.Adapter.Reception_Adapter;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.Check_main;
import com.assets.util.TrustAllCerts;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/20.
 */

public class Add_consumable extends Activity {
    private Spinner sp_add;
    private EditText add_number;
    private Button bt_add,sa_data;
    private ListView add_lv;
    private List<String> num = new ArrayList<String>();
    private List<Map<String, Object>> lv_list = new ArrayList<Map<String, Object>>();
    private ArrayAdapter<String> adapter;
    private List<String> list = new ArrayList<String>();
    private List<String> lv_data = new ArrayList<String>();
    private String url ="http://"+ Url.IP+"/api/consumablesQuery";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_consumable);
        inview();
        load();
        sa_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lv_list.size()>0){

                    for (int i =0;i<lv_list.size();i++){
                        try {
                            JSONObject root= new JSONObject();
                            root.put("Number",lv_list.get(i).get("assetName"));
                            root.put("Name",lv_list.get(i).get("assetNumber"));
                            lv_data.add(String.valueOf(root));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    Intent intent = new Intent();
                    intent.putExtra("data",lv_data.toString());
                    Add_consumable.this.setResult(3,intent);
                    Add_consumable.this.finish();
                }

            }
        });
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(add_number.getText().toString().equals("")){
                    return;
                }
                for (int i = 0;i<list.size();i++){
                    if (sp_add.getSelectedItem().equals(list.get(i))){
                        if (Integer.valueOf(add_number.getText().toString())>Integer.valueOf(num.get(i))){
                            Toast.makeText(Add_consumable.this,"已超过库存数",Toast.LENGTH_SHORT).show();
                                return;
                        }
                    }
                }
                if (!add_number.getText().toString().equals("")&&list.size()>0){

                        for (int j = 0;j<lv_list.size();j++){
                            if (lv_list.get(j).get("assetNumber").equals(sp_add.getSelectedItem())){
                                lv_list.remove(j);
                            }
                        }

                    Collections.reverse(lv_list);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("assetNumber",sp_add.getSelectedItem());
                    map.put("assetName",add_number.getText().toString());
                    lv_list.add(map);
                    Collections.reverse(lv_list);
                    Reception_Adapter reception_adapter = new Reception_Adapter(Add_consumable.this,lv_list);
                    //设置适配器
                    add_lv.setAdapter(reception_adapter);

                }

            }
        });
        sp_add.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                Toast.makeText(Add_consumable.this,list.get(arg2)+"库存数为："+num.get(arg2),Toast.LENGTH_SHORT).show();
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }

    private void load() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("123123",responseData);
                    showResponse(responseData);

                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }.start();
    }

    private void showResponse(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                List<Check_main> userList = gson.fromJson(responseData, new TypeToken<List<Check_main>>(){}.getType());
                for(int i = 0;i < userList.size();i++){
                    list.add(userList.get(i).getName());
                    num.add(userList.get(i).getNum());
                }
                // 为下拉列表定义一个适配器，这里就用到里前面定义的list。
                adapter = new ArrayAdapter<String>(Add_consumable.this,
                        android.R.layout.simple_spinner_item, list);
                // 为适配器设置下拉列表下拉时的菜单样式。
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                // 将适配器添加到下拉列表上
                sp_add.setAdapter(adapter);
            }
        });
    }

    private void inview() {
        sp_add = (Spinner) findViewById(R.id.sp_add);
        add_number = (EditText) findViewById(R.id.add_number);
        bt_add = (Button) findViewById(R.id.bt_add);
        sa_data = (Button) findViewById(R.id.sa_data);
        add_lv = (ListView) findViewById(R.id.add_lv);

    }
}
